<template>
    <div style="margin: 20px 0;">
        <el-button type="primary" @click="handlerAdd">新增用户</el-button>
    </div>
    <div>
        <el-table :data="users" style="width: 100%; height: 500px">
            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="电话号码" prop="phone"></el-table-column>
            <el-table-column label="创建时间" prop="create_time" :formatter="resetDate"></el-table-column>
            <el-table-column label="所属角色" prop="role_id" :formatter="formatRole"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row._id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        <!-- 添加/编辑用户弹窗 -->
        <el-dialog v-model="userFormVisible" title="添加/编辑用户" width="500">
            <el-form :model="user" ref="userFormRef" label-width="100px" label-position="right" style="width: 400px;" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="user.username"/>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="user.password"/>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name"/>
                </el-form-item>
                <el-form-item label="角色" prop="role_id">
                    <el-select v-model="user.role_id" aria-placeholder="请点击选择">
                    <el-option v-for="option in roleOptions" :key="option._id" :label="option.name" :value="option._id">
                    </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="user.phone"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="user._id == null ? addData(userFormRef) : updateData(userFormRef)">确定</el-button>
                    <el-button @click="userFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
// 引入数据类型
import type { userInfoData } from '@/api/user/type';
import { nextTick, onMounted, reactive, ref } from 'vue';
// 引入角色小仓库
import useRoleStore from '@/store/modules/role';
// 引入角色数据类型
import type { roleInfoData } from '@/api/role/type';
import { formateDate } from '@/utils/dateUtils';
// 引入用户小仓库
import useUserStore from '@/store/modules/user';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
let userStore = useUserStore()
const roleStore = useRoleStore()
// 自定义校验规则
const validateUserName = (_rule:any,value:any,callback:any)=>{
    value = value.trim()
    const length = value && value.length
    const pwdReg = /^[a-zA-Z0-9_]+$/
    if (value === ""){
        callback(new Error("请输入账号"))
    }else if(length<4||length>12){
        callback(new Error("长度在4到12个字符之间"))
    }else if(!pwdReg.test(value)){
        callback(new Error("账号必须是英文，数字或下划线组成"))
    }else{
        callback()
    }
}
// 自定义校验规则
// 自定义手机号码校验规则
const validatePhone = (_rule:any,value:any,callback:any)=>{
    value = value.trim()
    const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (value === ""){
        callback(new Error("请输入手机号码"))
    }else if(!phoneReg.test(value)){
        callback(new Error("请输入正确的手机号码"))
    }else{
        callback()
    }
}
// 用户数据列表
const users = ref<userInfoData[] | undefined>([]);

// 表单元素对象，需要和el-form的ref属性值对应
const userFormRef = ref()
// 添加用户表单校验规则
const rules = reactive<FormRules>({
  username:[
    {required: true,validator: validateUserName,trigger:['blur','change']},
  ],
  password:[
    {required: true, message:'请输入密码', trigger:'blur'},
    // {min:3,message:'密码长度需要大于4位',trigger:'blur'}
  ],
  name:[{required:true,message:'请输入姓名',trigger:'blur'}],
  role_id:[{required:true,message:'请选择角色',trigger:'blur'}],
  phone:[
    {required: true, validator: validatePhone, trigger:['blur','change']}
  ]
})
const handleEdit = (_id: string) => {
    handlerAdd()
    userStore.getUserById(_id).then(response=>{
        // @ts-ignore
        user.value = response
    })
}
const handleDelete = (_id: string) => {
    ElMessageBox.confirm(
    '确定要删除此条数据吗？',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        userStore.deleteUser(_id).then(()=>{
            getUserList()
            ElMessage({
            type: 'success',
            message: '删除成功',
            })
        })
    })
    .catch(() => {
    })
};
// 角色列表
const roleOptions = ref<roleInfoData[] | undefined>([])
// 获取角色列表
const getRoleList = () => {
    roleStore.getRoleList().then(() => {
        roleOptions.value = roleStore.roles
    })
}

// 格式化角色名称方法
const formatRole = (_row: any, _colum: any, cellValue: string, _index: number) => {
    let role = roleOptions.value?.find(item => item._id == cellValue)
    return role?.name
}
// 格式化日期数据 row：当前要格式化数据所在行对象，colum：列对象，cellValue：要格式化的数据
const resetDate = (_row: any, _colum: any, cellValue: number, _index: number) => {
    return formateDate(cellValue)
}
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
// 当每页显示条数发生变化
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    getUserList()
}
// 当页码发生变化
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    getUserList()
}
// 获取用户列表
const getUserList = ()=>{
    userStore.getUserList({page:currentPage.value,size:pageSize.value}).then(response=>{
        users.value = userStore.users
        total.value = (response?.total as number)
    })
}
// 打开添加用户对话框
const handlerAdd = ()=>{
    // 每次弹窗显示之前先初始化一下user对象,防止编辑之后user对象内一直存储信息,_id不再为null,无法进行添加操作
    user.value = {
        _id: null,
        username: '',
        password:'',
        name:'',
        phone:'',
        role_id:''
    }
    userFormVisible.value = true
    // 解决bug清空表单数据
    nextTick(()=>{
        userFormRef.value?.resetFields()
    })
}
// 添加用户ref对象
const userFormVisible = ref(false)
// 添加或编辑用户数据对象
const user = ref({
    _id:null,
    username:'',
    password:'',
    name: '',
    phone: '',
    role_id:'',
})
// 添加用户
const addData = (formEl:FormInstance | undefined)=>{
    if(!formEl)return
    formEl.validate((valid)=>{
        if(valid){
            userStore.addUser((user.value as userInfoData)).then(()=>{
                userFormVisible.value = false
                getUserList()
            })
        }else{
            console.log('error submit!');
        }
    })
}
// 编辑用户
const updateData = (formEl:FormInstance | undefined)=>{
    if(!formEl)return
    formEl.validate((valid)=>{
        if(valid){
            userStore.updateUser((user.value as userInfoData)).then(()=>{
                userFormVisible.value = false
                getUserList()
            })
        }else{
            console.log('error!');
        }
    })
}

onMounted(() => {
    getRoleList()
    getUserList()
})
</script>

<style scoped></style>